package com.leha.mp.core.services.imp;

import com.leha.mp.core.constants.BizConstants;
import com.leha.mp.core.dao.PlConsultingMapper;
import com.leha.mp.core.dao.PlUserVipMapper;
import com.leha.mp.core.entity.mybatis.PlConsulting;
import com.leha.mp.core.entity.mybatis.PlUserVip;
import com.leha.mp.core.entity.mybatis.PlUserVipKey;
import com.leha.mp.core.services.OrderServices;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yanming
 * @date 2018/07/11
 */

@Service
public class CommonServicesImpl {

    @Autowired
    OrderServices orderServices;

    @Autowired
    PlUserVipMapper plUserVipMapper;

    @Autowired
    PlConsultingMapper plConsultingMapper;

    /**
     * 咨询退款
     * @param consulting PlConsulting
     * @param  consultingStatus Byte 预约状态更改
     * @return boolean
     */
    public boolean refundMoneyForConsult(PlConsulting consulting, Byte consultingStatus) {
        try {
            if(consulting.getOrderId()!=0) {
                orderServices.cancelOrder(consulting.getOrderId());
            } else {
                refundConsultForVips(consulting.getUserId(), consulting.getDoctorId(), consulting.getConsultingType());
            }
            consulting.setStatus(consultingStatus);
            return plConsultingMapper.updateByPrimaryKeySelective(consulting) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 更新vip用户咨询次数
     * @param userId Integer
     * @param doctorId Integer
     * @param consultingType Integer
     */
    public void refundConsultForVips(Integer userId, Integer doctorId, Byte consultingType) {
        PlUserVipKey key = new PlUserVipKey();
        key.setDoctorId(doctorId);
        key.setUserId(userId);
        PlUserVip u = plUserVipMapper.selectByPrimaryKey(key);

        switch (consultingType) {
            case BizConstants.Consulting_Type_Msg:
                u.setMsgTimesLeft(u.getMsgTimesLeft()+1);
                break;
            case BizConstants.Consulting_Type_Video:
                u.setVideoTimesLeft(u.getVideoTimesLeft()+1);
                break;
            case BizConstants.Consulting_Type_Phone:
                u.setPhoneTimesLeft(u.getPhoneTimesLeft()+1);
                break;
                default:
                    // do nothing
                    break;
        }

        plUserVipMapper.updateByPrimaryKeySelective(u);
    }
}
